<!-- 告警模板配置 -->
<template>
	<div class="alarmTemplateContainer">
		<!-- 搜索条件 -->
		<yd-form :options="formOptions" :model="formData" :btns="formBtns"></yd-form>

		<!--查询列表-->
		<YdTable
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			ref="multipleTable"
			@sizeChangeHandler="queryGrid"
			@currentChangeHandler="queryGrid"
			@sortChangeHandler="queryGrid"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="open" width="700px" append-to-body center @close="cancel" :close-on-click-modal="false">
			<el-form ref="conForm" :model="form" :rules="rules" label-width="100px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="模板类型:" prop="type">
							<el-select v-model="form.type" placeholder="请选择" :disabled="typeDisabled" style="width: 200px">
								<el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="模板名称:" prop="name">
							<el-input v-model="form.name" placeholder="请输入模板名称" :disabled="nameDisabled" style="width: 200px" maxlength="50" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="模板说明:">
							<el-input
								v-model="form.description"
								type="textarea"
								:placeholder="descriptionPlaceHolder"
								:disabled="inputReadOnly"
								maxlength="200"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="模板内容:" prop="content">
							<el-input
								v-model="form.content"
								type="textarea"
								placeholder="请输入模板内容"
								rows="5"
								:disabled="inputReadOnly"
								maxlength="200"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24" align="right" class="el-col-Variable">
						<el-link @click="showVariable">模板变量查看</el-link>
					</el-col>
				</el-row>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="submitForm" v-if="showSubmit">确 定</el-button>
				<el-button @click="cancel" v-if="showSubmit">取 消</el-button>
				<el-button type="primary" @click="cancel" v-if="showClose">关 闭</el-button>
			</template>
		</el-dialog>

		<el-dialog title="模板变量" v-model="openVariable" width="800px" center>
			<div style="height: 480px" align="center">
				<!--查询列表-->
				<YdTable :formData="variableFormData" :tableConfig="variableTableConfig" :tableData="variableTableData" ref="variableMultipleTable">
				</YdTable>
			</div>
			<template #footer class="dialog-footer">
				<el-button @click="variableCancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="AlarmTemplate" lang="tsx">
import {
	queryAlarmTemplateList,
	queryAlarmTemplate,
	addTemplate,
	editTemplate,
	editTemplateEnable,
	deleteTemplateByIds,
	queryAlarmByTemplateId,
} from '@/api/management/alarmManage/alarmTemplateConfig';
import { getDicts } from '@/api/admin/dict/data';
import { ref, reactive, onMounted } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();

const statusOptions = ref<any>([
	{ label: '是', value: 0 },
	{ label: '否', value: 1 },
]);
// 遮罩层
const loading = ref(true);
const typeOptions = ref<any>([]);
const variableOptions = ref<any>([]);
// 选中数组
const ids = ref<any>([]);
// 选中状态数组
const enables = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 表单参数
let form = ref<anyObj>({});
// 是否显示弹出层
const open = ref(false);
const openVariable = ref(false);
//修改禁用类型和名称不能修改
const typeDisabled = ref(false);
const nameDisabled = ref(false);
//是否显示确认提交按钮，查看详情的时候不需要确认按钮
const showSubmit = ref(true);
const showClose = ref(false);
const inputReadOnly = ref(false);
//模板说明文字
const descriptionPlaceHolder = ref('请输入模板说明');
// 表单校验
const rules = ref({
	type: [{ required: true, message: '模板类型不能为空', trigger: 'change' }],
	name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
	content: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
});
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '模板类型',
		prop: 'type',
		children: [
			{ value: 1, label: '基础告警' },
			{ value: 2, label: '自定义告警' },
		],
		selectKey: 'value',
		isInitValue: false,
	},
	{
		type: 'select',
		label: '是否启用',
		prop: 'isEnable',
		children: statusOptions,
		selectKey: 'value',
		isInitValue: false,
	},
	{
		type: 'input',
		label: '模板名称',
		prop: 'name',
		attrs: {
			clearable: true,
		},
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: searchHandler,
	},
]);
// 搜索表单数据
let formData = reactive<anyObj>({});
// 列表配置
let tableConfig = reactive({
	url: queryAlarmTemplateList,
	columns: [
		{
			label: '模板类型',
			prop: 'typeName',
			width: 100,
		},
		{
			label: '模板名称',
			prop: 'name',
			width: 230,
		},
		{
			label: '启用状态',
			prop: 'isEnable',
			width: 100,
			render: (row: anyObj, val: ApiVal) => {
				// if (proxy.checkRole(['admin']) || proxy.checkPermi(['alarmTemplate:isEnable'])) {
				return <el-switch v-model={row.isEnable} activeValue={0} inactiveValue={1} onChange={() => handleEnableChange(row)}></el-switch>;
				// }
				// return (
				//     <el-switch v-model={row.isEnable} disabled activeValue={0} inactiveValue={1}></el-switch>
				// )
			},
		},
		{
			label: '模板内容',
			prop: 'content',
			align: 'left',
		},
		{
			label: '操作',
			prop: '',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope: anyObj) => getDetailHandle(scope.row),
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['alarmTemplate:add'], handler: () => handleAdd() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['alarmTemplate:edit'], disable: 'single', handler: () => handleUpdate() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['alarmTemplate:delete'], disable: 'multiple', handler: () => handleDelete() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = ref([]);
// 模板变量
let variableFormData = reactive<anyObj>({});
// 列表配置
let variableTableConfig = reactive({
	columns: [
		{
			label: '变量',
			prop: 'value',
		},
		{
			label: '变量说明',
			prop: 'label',
		},
	],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: false,
	// 加载层
	loading: true,
	height: '500px',
});
// 列表数据
let variableTableData = ref([]);
const conForm = ref<any>();
const multipleTable = ref<any>();

onMounted(() => {
	//从数据字典里面查询模板类型
	getDicts('conf_alarm_template_type').then((response: ApiResponse) => {
		let data = response.data;
		for (var i = 0; i < data.length; i++) {
			let temp: anyObj = {};
			temp.value = parseInt(data[i].value);
			temp.label = data[i].label;
			typeOptions.value.push(temp);
		}
	});
	searchHandler();
});

// 搜索
function searchHandler() {
	formData.pageNum = 1;
	queryGrid();
}
// 查询列表
function queryGrid() {
	loading.value = true;
	queryAlarmTemplateList(formData).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			tableConfig.loading = false;
			return;
		}
		tableConfig.loading = false;
		tableData.value = res.data.records;
		tableConfig.pagination.total = res.data.total;
	});
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: anyObj) => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
	enables.value = selection.map((item: anyObj) => item.isEnable);
}
// 禁用启用
function handleEnableChange(row: anyObj) {
	queryAlarmByTemplateId(row.id).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			loading.value = false;
			return;
		}
		let dm = res.data;
		if (dm != null && dm != '') {
			proxy.$modal.msgWarning('已经有下列告警引用到该模板，请解绑关系后再禁用：' + dm);
			row.isEnable = row.isEnable === 0 ? 1 : 0;
			return;
		}
		const data = {
			isEnable: row.isEnable,
			id: row.id,
		};
		//本来是启用状态，现在禁用
		if (row.isEnable == 1) {
			//在模版禁用时，需要查询m_alarms表里面是否有引用该模版，如果有需提示哪些告警引用到该模版，需解绑关系后才能禁用模版。
			let text = row.name;
			proxy.$modal
				.confirm('确认要禁用 ' + text + ' 模板吗?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					cancelButtonClass: 'confirm-rigth-cancel-button',
					type: 'warning',
				})
				.then(function () {
					return editTemplateEnable(data);
				})
				.then(() => {
					proxy.$modal.msgSuccess('禁用 ' + text + ' 模板成功');
				})
				.catch(function () {
					row.isEnable = row.isEnable === 0 ? 1 : 0;
				});
		} else {
			editTemplateEnable(data).then((res) => {
				if (res.code !== 0) {
					proxy.$modal.msgWarning(res.msg);
					loading.value = false;
					return;
				}
				proxy.$modal.msgSuccess('启用成功');
			});
		}
	});
	multipleTable.value.getTableRef().clearSelection();
	ids.value = [];
	enables.value = [];
}
/** 新增按钮操作 */
function handleAdd() {
	reset();
	title.value = '增加模板';
	open.value = true;
	typeDisabled.value = false;
	nameDisabled.value = false;
	showSubmit.value = true;
	showClose.value = false;
	inputReadOnly.value = false;
	descriptionPlaceHolder.value = '请输入模板说明';
}
/** 修改按钮操作 */
function handleUpdate() {
	reset();
	title.value = '修改模板';
	typeDisabled.value = true;
	nameDisabled.value = true;
	open.value = true;
	showSubmit.value = true;
	showClose.value = false;
	inputReadOnly.value = false;
	descriptionPlaceHolder.value = '请输入模板说明';
	const id = ids;
	if (id.value == null || id.value == '') {
		proxy.$modal.msgWarning('请选择要修改的模板。');
		return;
	}
	queryAlarmTemplate(id.value).then((response) => {
		form.value = response.data;
	});
}
/** 删除按钮操作 */
function handleDelete() {
	if (ids.value == null) {
		proxy.$modal.msgWarning('请选择要删除的模板。');
		return;
	}
	if (enables.value.length > 0) {
		for (let i = 0; i < enables.value.length; i++) {
			if (enables.value[i] === 0) {
				proxy.$modal.msgWarning('已经禁用状态的模板才删除！');
				return;
			}
		}
	}
	proxy.$modal
		.confirm('是否需要删除已经勾选的模板数据?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(function () {
			return deleteTemplateByIds(ids.value);
		})
		.then(() => {
			searchHandler();
			proxy.$modal.msgSuccess('删除成功');
		})
		.catch(function () {});
}
/** 提交按钮 */
function submitForm() {
	conForm.value.validate((valid: any) => {
		if (valid) {
			if (form.value.id != undefined) {
				editTemplate(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('修改成功');
						open.value = false;
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			} else {
				addTemplate(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('新增成功');
						open.value = false;
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			}
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}
// 表单重置
function reset() {
	form.value = {
		type: undefined,
		name: undefined,
		description: undefined,
		content: undefined,
	};
	conForm.value?.resetFields();
}
function showVariable() {
	openVariable.value = true;
	variableOptions.value = [];
	//从数据字典里面查询模板类型
	getDicts('sys_alarm_template_variable').then((response: ApiResponse) => {
		let data = response.data;
		for (let i = 0; i < data.length; i++) {
			let temp: anyObj = {};
			temp.value = data[i].value;
			temp.label = data[i].label;
			variableOptions.value.push(temp);
		}
		variableTableData.value = variableOptions.value;
		variableTableConfig.loading = false;
	});
}
// 模板变量按钮
function variableCancel() {
	openVariable.value = false;
}
//显示详情
function getDetailHandle(row: anyObj) {
	reset();
	title.value = '模板详情';
	open.value = true;
	showSubmit.value = false;
	showClose.value = true;
	inputReadOnly.value = true;
	typeDisabled.value = true;
	nameDisabled.value = true;
	descriptionPlaceHolder.value = '';
	const id = row.id;
	queryAlarmTemplate(id).then((response) => {
		form.value = response.data;
	});
}
</script>

<style rel="stylesheet/scss" lang="scss"></style>
